package example.sensor.com.sensorexample;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileWriter;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import example.sensor.com.sensorexample.utils.DateUtil;
import example.sensor.com.sensorexample.utils.ToastUtil;
import pub.devrel.easypermissions.EasyPermissions;

public class MainActivity extends AppCompatActivity implements SensorEventListener, View.OnClickListener {

    private TextView mtextViewx;
    private TextView mtextViewy;
    private TextView mtextViewz;
    private TextView mtextViewlx;
    private TextView mtextViewly;
    private TextView mtextViewlz;
    private TextView mtextViewgx;
    private TextView mtextViewgy;
    private TextView mtextViewgz;
    private TextView mtextView1;
    private TextView mtextView2;
    private TextView mtextView3;
    private TextView mtextView4;
    private TextView mtextView5;
    private TextView mtextView6;
    private TextView mtextView7;
    private TextView mtextView8;
    private TextView mtextView9;
    private TextView mtextView10;
    private TextView mtextView11;
    private TextView mtextView12;
    private TextView mtextView13;
    private TextView mtextView14;
    private TextView mtextView15;

    private TextView tvOutput;
    private SensorManager sm;
    private static final String TAG = "sensor";

    public String txt;
    String filePath = "/sdcard/sensordata/readfile/";
    String fileName = "log.txt";
    String fileNameWifi = "wifiMap.txt";
    private int HZ = 10000;
    WifiManager wifiManager;
    WifiInfo wifiInfo;
    LocationManager locationManager;
    private String provider;
    SensorEvent sensorEventAll;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        getPermission();

        writeTxtToFile("% Sensors:" + "\n", filePath, fileName);

        sm = (SensorManager) getSystemService(SENSOR_SERVICE);
        List<Sensor> sensorList = sm.getSensorList(Sensor.TYPE_ALL);
        for (Sensor sensor : sensorList) {
            writeTxtToFile("% " + sensor.getName() + "\n", filePath, fileName);
        }

        // 获得WifiManager
        wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
        wifiInfo = wifiManager.getConnectionInfo();


        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        provider = LocationManager.GPS_PROVIDER;
        //获取LocationManager
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            return;
        }
        locationManager.requestLocationUpdates(provider, 10, 0.01f, locationListener);

        initView();
        wifiChange();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        sm.unregisterListener(this);
    }

    public void getPermission() {
        String[] perms = {android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE,
                android.Manifest.permission.ACCESS_WIFI_STATE, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.INTERNET};
        if (EasyPermissions.hasPermissions(this, perms)) {
        } else {
            EasyPermissions.requestPermissions(this, "该应用需要",
                    0, perms);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        setSensor();
        SensorManager mSensorManager;
        List<Sensor> sensorList;
        // 实例化传感器管理者
        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        // 得到设置支持的所有传感器的List
        sensorList = mSensorManager.getSensorList(Sensor.TYPE_ALL);
        List<String> sensorNameList = new ArrayList<String>();
        for (Sensor sensor : sensorList) {
            Log.d(TAG, "onResume: "+sensor.getName());
        }
    }

    public void initView() {
        mtextViewx = (TextView) findViewById(R.id.textViewx);
        mtextViewy = (TextView) findViewById(R.id.textViewy);
        mtextViewz = (TextView) findViewById(R.id.textViewz);
        mtextViewlx = (TextView) findViewById(R.id.textViewlx);
        mtextViewly = (TextView) findViewById(R.id.textViewly);
        mtextViewlz = (TextView) findViewById(R.id.textViewlz);
        mtextViewgx = (TextView) findViewById(R.id.textViewgx);
        mtextViewgy = (TextView) findViewById(R.id.textViewgy);
        mtextViewgz = (TextView) findViewById(R.id.textViewgz);
        mtextView1 = (TextView) findViewById(R.id.textView1);
        mtextView2 = (TextView) findViewById(R.id.textView2);
        mtextView3 = (TextView) findViewById(R.id.textView3);
        mtextView4 = (TextView) findViewById(R.id.textView4);
        mtextView5 = (TextView) findViewById(R.id.textView5);
        mtextView6 = (TextView) findViewById(R.id.textView6);
        mtextView7 = (TextView) findViewById(R.id.textView7);
        mtextView8 = (TextView) findViewById(R.id.textView8);
        mtextView9 = (TextView) findViewById(R.id.textView9);
        mtextView10 = (TextView) findViewById(R.id.textView10);
        mtextView11 = (TextView) findViewById(R.id.textView11);
        mtextView12 = (TextView) findViewById(R.id.textView12);
        mtextView13 = (TextView) findViewById(R.id.textView13);
        mtextView14 = (TextView) findViewById(R.id.textView14);
        mtextView15 = (TextView) findViewById(R.id.textView15);

        tvOutput = (TextView) findViewById(R.id.tv_output);
        tvOutput.setOnClickListener(this);
    }

    public void setSensor() {
        //创建一个SensorManager来获取系统的传感器服务
        sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        /*
         * 最常用的一个方法 注册事件
         * 参数1 ：SensorEventListener监听器
         * 参数2 ：Sensor 一个服务可能有多个Sensor实现，此处调用getDefaultSensor获取默认的Sensor
         * 参数3 ：模式 可选数据变化的刷新频率，多少微秒取一次。
         * */
        //加速度传感器
        sm.registerListener(this, sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), HZ);
        // 为磁场传感器注册监听器
        sm.registerListener(this, sm.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD), HZ);
        // 为方向传感器注册监听器
        sm.registerListener(this, sm.getDefaultSensor(Sensor.TYPE_ORIENTATION), HZ);
        // 为陀螺仪传感器注册监听器
        sm.registerListener(this, sm.getDefaultSensor(Sensor.TYPE_GYROSCOPE), HZ);
        // 为重力传感器注册监听器
        sm.registerListener(this, sm.getDefaultSensor(Sensor.TYPE_GRAVITY), HZ);
        // 为线性加速度传感器注册监听器
        sm.registerListener(this, sm.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION), HZ);
        // 为温度传感器注册监听器
        sm.registerListener(this, sm.getDefaultSensor(Sensor.TYPE_TEMPERATURE), HZ);
        Sensor tempertureSensor = sm.getDefaultSensor(Sensor.TYPE_PRESSURE);
//        if (tempertureSensor == null) {
//            Toast.makeText(this, "你的设备不支持该功能", 0).show();
//        }
        // 为光传感器注册监听器
        sm.registerListener(this, sm.getDefaultSensor(Sensor.TYPE_LIGHT), HZ);
        // 为距离传感器注册监听器
        sm.registerListener(this, sm.getDefaultSensor(Sensor.TYPE_PROXIMITY), HZ);
        // 为压力传感器注册监听器
        sm.registerListener(this, sm.getDefaultSensor(Sensor.TYPE_PRESSURE), HZ);
        // 计步统计
        sm.registerListener(this, sm.getDefaultSensor(Sensor.TYPE_STEP_COUNTER), HZ);
        // 单次计步
        sm.registerListener(this, sm.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR), HZ);
    }

    @Override
    public void onSensorChanged(final SensorEvent sensorEvent) {
        sensorEventAll = sensorEvent;

        Calendar CD = Calendar.getInstance();
        if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
            float X_lateral = sensorEvent.values[0];
            float Y_longitudinal = sensorEvent.values[1];
            float Z_vertical = sensorEvent.values[2];
            mtextViewx.setText(X_lateral + "");
            mtextViewy.setText(Y_longitudinal + "");
            mtextViewz.setText(Z_vertical + "");

            txt = "ACCE;" + CD.get(Calendar.MILLISECOND) + ";" + sensorEvent.timestamp + ";" + X_lateral + ";" + Y_longitudinal + ";" + Z_vertical + "\n";
            writeTxtToFile(txt,filePath,fileName);
        }
        else if(sensorEvent.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD){
            float X_lateral = sensorEvent.values[0];
            float Y_longitudinal = sensorEvent.values[1];
            float Z_vertical = sensorEvent.values[2];
            mtextView1.setText("x轴的磁场强度\n"+ X_lateral );
            mtextView2.setText("y轴的磁场强度\n"+ Y_longitudinal );
            mtextView3.setText("z轴的磁场强度\n"+ Z_vertical );

            txt = "MAGN;" + CD.get(Calendar.MILLISECOND) + ";" + sensorEvent.timestamp + ";" + X_lateral + ";" + Y_longitudinal + ";" + Z_vertical + "\n";
            writeTxtToFile(txt,filePath,fileName);
        }
        else if(sensorEvent.sensor.getType() == Sensor.TYPE_ORIENTATION){
            float X_lateral = sensorEvent.values[0];
            float Y_longitudinal = sensorEvent.values[1];
            float Z_vertical = sensorEvent.values[2];
            mtextView4.setText("绕z轴转过的角度\n"+ X_lateral );
            mtextView5.setText("绕x轴转过的角度\n"+ Y_longitudinal );
            mtextView6.setText("绕y轴转过的角度\n"+ Z_vertical );

            txt = "AHRS;" + CD.get(Calendar.MILLISECOND) + ";" + sensorEvent.timestamp + ";" + X_lateral + ";" + Y_longitudinal + ";" + Z_vertical + "\n";
            writeTxtToFile(txt,filePath,fileName);
        }
        else if(sensorEvent.sensor.getType() == Sensor.TYPE_GYROSCOPE){
            //需要将弧度转为角度
            float X = (float)Math.toDegrees(sensorEvent.values[0]);
            float Y = (float)Math.toDegrees(sensorEvent.values[1]);
            float Z = (float)Math.toDegrees(sensorEvent.values[2]);
            mtextView7.setText("绕x轴转过的角速度\n"+ X );
            mtextView8.setText("绕y轴转过的角速度\n"+ Y );
            mtextView9.setText("绕z轴转过的角速度\n"+ Z );

            txt = "GYRO;" + CD.get(Calendar.MILLISECOND) + ";" + sensorEvent.timestamp + ";" + X + ";" + Y + ";" + Z + "\n";
            writeTxtToFile(txt,filePath,fileName);
        }else if(sensorEvent.sensor.getType() == Sensor.TYPE_GRAVITY){
            float X = sensorEvent.values[0];
            float Y = sensorEvent.values[1];
            float Z = sensorEvent.values[2];
            mtextViewgx.setText("x方向的重力加速度\n"+ X );
            mtextViewgy.setText("Y方向的重力加速度\n"+ Y );
            mtextViewgz.setText("Z方向的重力加速度\n"+ Z );

            txt = "GRAV;" + CD.get(Calendar.MILLISECOND) + ";" + sensorEvent.timestamp + ";" + X + ";" + Y + ";" + Z + "\n";
            writeTxtToFile(txt,filePath,fileName);
        }else if(sensorEvent.sensor.getType() == Sensor.TYPE_LINEAR_ACCELERATION){
            float X = sensorEvent.values[0];
            float Y = sensorEvent.values[1];
            float Z = sensorEvent.values[2];
            mtextViewlx.setText("x方向的线性加速度\n"+ X );
            mtextViewly.setText("Y方向的线性加速度\n"+ Y );
            mtextViewlz.setText("Z方向的线性加速度\n"+ Z );
        }else if(sensorEvent.sensor.getType() == Sensor.TYPE_TEMPERATURE){
            float X = sensorEvent.values[0];
            mtextView10.setText("温度为"+ X );
        }else if(sensorEvent.sensor.getType() == Sensor.TYPE_LIGHT){
            float X = sensorEvent.values[0];
            mtextView11.setText("光强度为为"+ X );
        }else if(sensorEvent.sensor.getType() == Sensor.TYPE_PROXIMITY){
            float X = sensorEvent.values[0];
            mtextView12.setText("距离为"+ X );
        }else if(sensorEvent.sensor.getType() == Sensor.TYPE_PRESSURE){
            float X = sensorEvent.values[0];
            mtextView13.setText("压强为"+ X );

            txt = "PRES;" + CD.get(Calendar.MILLISECOND) + ";" + sensorEvent.timestamp + ";" + X + "\n";
            writeTxtToFile(txt,filePath,fileName);
        }
        else if(sensorEvent.sensor.getType() == Sensor.TYPE_STEP_COUNTER){
            float X = sensorEvent.values[0];
            mtextView14.setText("COUNTER："+ X );
        } else if(sensorEvent.sensor.getType() == Sensor.TYPE_STEP_DETECTOR){
            float X = sensorEvent.values[0];
            mtextView15.setText("DECTOR："+ X );
        }
    }

    public void wifiChange() {
        //if (sensorEventAll == null) return;
        /*Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                Calendar CD = Calendar.getInstance();
                txt = "WIFI;" + CD.get(Calendar.MILLISECOND) + ";" + wifiInfo.getMacAddress() + ";" + wifiInfo.getRssi() + "\n";
                writeTxtToFile(txt,filePath,fileNameWifi);
            }
        }, 1000, 100);*/
    }

    //LocationListener 用于当位置信息变化时由 locationManager 调用
    LocationListener locationListener = new LocationListener(){

        @Override
        public void onLocationChanged(Location location) {
            if (sensorEventAll == null) return;
            // TODO Auto-generated method stub
            //更新当前设备的位置信息
            Calendar CD = Calendar.getInstance();
            txt = "GPRS;" + CD.get(Calendar.MILLISECOND) + ";" + sensorEventAll.timestamp + ";" + location.getLongitude() + ";" +
                    location.getLatitude() + ";" + location.getBearing() + ";" + location.getAccuracy() + ";" + location.getSpeed()
                    + "\n";
            writeTxtToFile(txt,filePath,fileName);
        }

        @Override
        public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            // TODO Auto-generated method stub

        }

    };

    //复写onAccuracyChanged方法
    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
        Log.i(TAG, "onAccuracyChanged");
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_output:

                break;
        }
    }

    // 将字符串写入到文本文件中
    public void writeTxtToFile(final String strcontent, final String filePath, final String fileName) {
        //生成文件夹之后，再生成文件，不然会出错
        makeFilePath(filePath, fileName);

        Runnable runnable=new Runnable() {
            @Override
            public void run() {
                try {
                    String strFilePath = filePath + fileName;
                    // 每次写入时，都换行写
                    String strContent = strcontent;

                    File file = new File(strFilePath);
                    if (!file.exists()) {
                        Log.d("TestFile", "Create the file:" + strFilePath);
                        file.getParentFile().mkdirs();
                        file.createNewFile();
                    }
                    RandomAccessFile raf = new RandomAccessFile(file, "rwd");
                    raf.seek(file.length());
                    raf.write(strContent.getBytes());
                    raf.close();
                } catch (Exception e) {
                    Log.e("TestFile", "Error on write File:" + e);
                }
            }
        };

        Thread mt1 = new Thread(runnable, "窗口1");

        // 步骤4：通过 线程对象 控制线程的状态，如 运行、睡眠、挂起  / 停止
        mt1.start();

    }

    // 生成文件
    public File makeFilePath(String filePath, String fileName) {
        File file = null;
        makeRootDirectory(filePath);
        try {
            file = new File(filePath + fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }

    // 生成文件夹
    public static void makeRootDirectory(String filePath) {
        File file = null;
        try {
            file = new File(filePath);
            if (!file.exists()) {
                file.mkdirs();
            }
        } catch (Exception e) {
            Log.i("error:", e+"");
        }
    }
}
